<template>
  <div class="container">
    <div class="resume-list">
      <div class="list-header">
        <h3>初筛通过简历列表（{{ candidates.length }}人）</h3>
      </div>
      <ul>
        <li
          v-for="item in candidates"
          :key="item.id"
          :class="{ selected: selectedResume && selectedResume.id === item.id }"
          @click="selectResume(item)"
        >
          <!-- 头像 -->
          <img
            :src="item.deliverjob.jobinfo.aveter || defaultAvatar"
            class="avatar"
            :alt="item.deliverjob.jobinfo.name"
          >
          <!-- 核心信息 -->
          <div class="candidate-info">
            <div class="name-score">
              <span class="candidate-name">姓名：{{ item.deliverjob.jobinfo.name }}</span>
              <span class="score-tag" :style="{ background: getScoreColor(item.ai_match_score) }">
                匹配分：{{ item.ai_match_score }}
              </span>
            </div>
            <div class="resume-meta">
              简历详情：<a :href="item.deliverjob.jobinfo.resume_url" target="_blank" class="resume-link">查看简历</a>
            </div>
            <div class="base-info">
              <span class="education">学历：{{ educationMap[item.deliverjob.jobinfo.education] || '未知' }}</span>
              <span class="sex">性别：{{ item.deliverjob.jobinfo.sex === 1 ? '男' : '女' }}</span>
            </div>
            <div class="desc">个人介绍：{{ item.deliverjob.jobinfo.description || '无' }}</div>
            <!-- 初筛状态标签 -->
            <div class="status-tag">
              <el-tag type="success" size="small">初筛通过</el-tag>
              <span class="time">处理时间：{{ formatTime(item.end_at) }}</span>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <div class="screening-result">
      <h3>AI初筛报告</h3>
      <div v-if="screeningResult && selectedResume">
        <!-- 个人详细信息 -->
        <div class="personal-info">
          <h4>个人信息</h4>
          <el-descriptions column="2" border>
            <el-descriptions-item label="姓名">{{ selectedResume.deliverjob.jobinfo.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ selectedResume.deliverjob.jobinfo.sex === 1 ? '男' : '女' }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ selectedResume.deliverjob.jobinfo.birthdate || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="学历">{{ educationMap[selectedResume.deliverjob.jobinfo.education] || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="求职状态">{{ getCurrentStatus(selectedResume.deliverjob.jobinfo.current_status) }}</el-descriptions-item>
            <el-descriptions-item label="投递时间">{{ formatTime(selectedResume.deliverjob.created_at) }}</el-descriptions-item>
          </el-descriptions>
          <div class="resume-link-wrap">
            <a :href="selectedResume.deliverjob.jobinfo.resume_url" target="_blank" class="resume-link">查看完整简历</a>
          </div>
          <div class="description">
            <p>个人介绍：{{ selectedResume.deliverjob.jobinfo.description || '无' }}</p>
          </div>
        </div>

        <!-- 初筛结论 -->
        <div class="evaluation">
          <h4>初筛结论</h4>
          <div class="score-card">
            <div class="score-item">
              <span class="label">匹配加分：</span>
              <span class="value">{{ screeningResult.ai_match_score }}</span>
            </div>
            <div class="score-item">
              <span class="label">检索评分：</span>
              <span class="value">{{ screeningResult.ai_search_score }} / 总分10</span>
            </div>
          </div>

          <div class="evaluation-section">
            <h5>候选人优势：</h5>
            <ul class="points match-points">
              <li v-for="(point, idx) in screeningResult.ai_match_points" :key="idx">
                <i class="el-icon-check-circle"></i> {{ point }}
              </li>
            </ul>
          </div>

          <div class="evaluation-section">
            <h5>候选人风险点：</h5>
            <ul class="points risk-points">
              <li v-for="(point, idx) in screeningResult.ai_risk_points" :key="idx">
                <i class="el-icon-warning"></i> {{ point }}
              </li>
            </ul>
          </div>

          <div class="evaluation-section">
            <h5>HR视角分析：</h5>
            <p class="hr-evaluation">{{ screeningResult.hr_evaluation }}</p>
          </div>

          <div class="evaluation-section">
            <h5>求职者建议：</h5>
            <p class="user-evaluation">{{ screeningResult.user_evaluation }}</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="goToChat(selectedResume.deliverjob.jobinfo.user)">
            <i class="el-icon-chat-line-round"></i> 与求职者聊天
          </el-button>
          <el-button type="success" style="margin-left: 10px;">
            <i class="el-icon-check"></i> 进入二面
          </el-button>
          <el-button type="danger" style="margin-left: 10px;">
            <i class="el-icon-close"></i> 淘汰
          </el-button>
        </div>
      </div>
      <div v-else>
        <el-empty description="请选择左侧简历查看详情" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElTag, ElDescriptions, ElDescriptionsItem, ElButton, ElEmpty, ElIcon } from 'element-plus'

// 路由与状态管理
const route = useRoute()
const router = useRouter()
const job_id = route.query.job_id
const candidates = ref([])
const selectedResume = ref(null)
const screeningResult = ref(null)
let ws = null
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec6438fd16fc7d2f7266e320f1.png' // 默认头像

// 学历映射
const educationMap = {
  1: '小学',
  2: '初中',
  3: '高中',
  4: '大专',
  5: '本科',
  6: '硕士',
  7: '博士'
}

// 求职状态映射
const getCurrentStatus = (status) => {
  const statusMap = {
    0: '在职-考虑机会',
    1: '在职-积极找工作',
    2: '离职-随时到岗'
  }
  return statusMap[status] || '未知'
}

// 时间格式化
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 匹配分颜色映射（越高越绿）
const getScoreColor = (score) => {
  if (score >= 40) return '#52c41a' // 绿色
  if (score >= 25) return '#faad14' // 黄色
  return '#f5222d' // 红色
}

// 获取初筛通过的简历列表
const fetchCandidates = async () => {
  try {
    const res = await axios.get('http://127.0.0.1:8000/job/passedResumes/', {
      params: { job_id }
    })
    candidates.value = res.data.data
  } catch (e) {
    console.error('获取简历列表失败:', e)
    ElNotification.error({ title: '错误', message: '获取简历列表失败' })
  }
}

// 选择简历，加载详情
const selectResume = (item) => {
  selectedResume.value = item
  screeningResult.value = item // 直接使用item作为详情数据（因返回数据已包含完整初筛信息）
}

// WebSocket连接（实时推送新简历）
const connectWebSocket = () => {
  ws = new WebSocket(`ws://127.0.0.1:8000/ws/screening/hr/${job_id}/`)

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data)
    if (data.type === 'screening_result') {
      // 新简历提示
      ElNotification({
        title: '新简历通过初筛',
        message: `求职者 ${data.evaluation.score_info.resume_name || '未知'} 已通过初筛`,
        type: 'success',
        duration: 5000,
        onClick: () => {
          // 点击通知自动选中新简历
          fetchCandidates().then(() => {
            const newResume = candidates.value.find(c => c.deliverjob.id === data.deliverjob_id)
            if (newResume) selectResume(newResume)
          })
        }
      })
      // 刷新列表
      fetchCandidates()
    }
  }

  ws.onerror = () => {
    ElNotification.error({ title: '错误', message: 'WebSocket连接异常' })
  }

  ws.onclose = () => {
    console.log('WebSocket连接关闭，尝试重连...')
    setTimeout(connectWebSocket, 3000) // 3秒后重连
  }
}

// 跳转到聊天页面
const goToChat = (userId) => {
  router.push({ path: '/chat', query: { user_id: userId, job_id } })
}

// 页面挂载时初始化
onMounted(() => {
  fetchCandidates()
  connectWebSocket()
})

// 页面卸载时关闭连接
onUnmounted(() => {
  if (ws) ws.close()
})
</script>

<style scoped>
.container {
  display: flex;
  gap: 24px;
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

/* 左侧简历列表 */
.resume-list {
  width: 420px;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.list-header {
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #eee;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2329;
}

.resume-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.resume-list li {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background 0.2s;
}

.resume-list li:hover {
  background: #f9fafb;
}

.resume-list li.selected {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
  float: left;
}

.candidate-info {
  margin-left: 62px;
}

.name-score {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.candidate-name {
  font-weight: 600;
  font-size: 16px;
  color: #1f2329;
}

.score-tag {
  padding: 2px 8px;
  border-radius: 12px;
  color: white;
  font-size: 12px;
  font-weight: 500;
}

.base-info {
  display: flex;
  gap: 16px;
  margin: 8px 0;
  font-size: 13px;
  color: #6b7280;
}

.desc {
  font-size: 13px;
  color: #4b5563;
  margin: 8px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
}

.time {
  font-size: 12px;
  color: #9ca3af;
}

/* 右侧详情区 */
.screening-result {
  flex: 1;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.screening-result h3 {
  margin-top: 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

/* 个人信息区 */
.personal-info {
  margin-bottom: 24px;
}

.resume-link-wrap {
  margin: 16px 0;
}

.resume-link {
  color: #1890ff;
  text-decoration: underline;
  font-size: 14px;
}

.description {
  margin-top: 12px;
  padding: 10px;
  background: #f9fafb;
  border-radius: 4px;
  line-height: 1.6;
}

/* 初筛结论区 */
.evaluation {
  margin-top: 24px;
}

.score-card {
  display: flex;
  gap: 20px;
  margin: 16px 0;
  padding: 16px;
  background: #f0f2f5;
  border-radius: 6px;
}

.score-item {
  display: flex;
  align-items: center;
}

.score-item .label {
  font-weight: 500;
  margin-right: 8px;
  color: #4b5563;
}

.score-item .value {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.evaluation-section {
  margin: 20px 0;
}

.evaluation-section h5 {
  margin: 0 0 12px 0;
  font-size: 15px;
  color: #1f2329;
}

.points {
  padding-left: 24px;
  margin: 0;
}

.points li {
  margin: 8px 0;
  line-height: 1.6;
  color: #4b5563;
}

.match-points i {
  color: #52c41a;
  margin-right: 8px;
}

.risk-points i {
  color: #faad14;
  margin-right: 8px;
}

.hr-evaluation, .user-evaluation {
  padding: 12px;
  background: #f9fafb;
  border-radius: 4px;
  line-height: 1.6;
  color: #4b5563;
}

/* 操作按钮 */
.action-buttons {
  margin-top: 30px;
  display: flex;
}
</style>